<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goodsAttrValues:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:goodsAttrValues:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="attrList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="goodsAttrValuesId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="属性" align="center" prop="attrName" />
      <el-table-column label="属性值" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="status">
        <!-- <template slot-scope="scope">
          {{ scope.row.status === 0 ? "正常" : "禁用" }}
        </template> -->
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:info:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改规格属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input
            v-model="form.goodsName"
            placeholder="请输入商品名称"
            disabled
          />
        </el-form-item>
        <el-form-item label="属性" prop="attrId">
          <el-select
            v-model="form.attrId"
            placeholder="请选择属性"
            @change="handleAttributeChange"
          >
            <el-option
              v-for="dict in attrAll"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性值" prop="attrValueId">
          <el-select v-model="form.attrValueId" placeholder="请选择属性值">
            <el-option
              v-for="dict in attrValues"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  listAttr,
  getAttr,
  delAttr,
  addAttr,
  updateAttr,
  getAttrAll,
  getAttrValues,
} from "@/api/goods/infoAttrValues";

export default {
  name: "Attr",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      imgFileList: [],
      goodsId: null, // 商品Id
      // 品牌信息
      attrAll: [],
      imageUrl: "",
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规格属性表格数据
      attrList: [],
      //规格属性值：
      attrValues: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        attrId: null,
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        brandName: null,
        orderNum: null,
        enabled: null,
        goodsId: null,
      },
      // 表单参数
      form: {
        status: "0",
      },
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        attrValueId: [
          { required: true, message: "属性值不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getAttrList();
  },
  methods: {
    handleAttributeChange() {
      this.attrValues = [];
      // 根据选中的属性ID，重新获取属性值
      getAttrValues({ attrId: this.form.attrId, goodsId: this.goodsId }).then((response) => {
        this.attrValues = response.rows.map((item) => ({
          value: item.id,
          label: item.name,
        }));
      });
    },
    getAttrList() {
      this.queryParams.goodsId = this.goodsId;
      getAttrAll(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.attrAll = response.rows.map((item) => ({
            value: item.id,
            label: item.name,
          }));
        }
      );
    },
    handleAuthRole(row) {
      const id = row.id;
      this.$router.push("/");
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // show(images) {
    //   if (images == "" || images == null) {
    //     return "http://localhost:8081/file/img3.jpg";
    //   } else {
    //     return `http://localhost:8081/file/${images}`;
    //   }
    // },
    /** 查询规格属性列表 */
    getList() {
      this.goodsId = this.$route.params.goodsId;
      this.queryParams.goodsId = this.goodsId;
      this.loading = true;
      listAttr(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.attrList = response.rows;
          
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsName: this.attrList[0].goodsName,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.goodsAttrValuesId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAttrList();
      this.open = true;
      this.title = "添加规格属性";
    },
    /** 提交按钮 */
    submitForm() {
      this.form.goodsId = this.goodsId;
      console.log("form:" + JSON.stringify(this.form, null, 2));

      this.$refs["form"].validate((valid) => {
        if (valid) {
          addAttr(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.goodsAttrValuesId || this.ids;
      this.$modal
        .confirm('是否确认删除规格属性编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAttr(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "goods/info/export",
        {
          ...this.queryParams,
        },
        `info_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "goods/info/importTemplate",
        {},
        `attr_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      console.log(this.form);
      this.$refs.upload.submit();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
